package cn.changshengjue.dakong.utils;

import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;

import cn.changshengjue.dakong.main;
import cn.changshengjue.dakong.command.CommandHandler;
import cn.changshengjue.dakong.listener.ExamplesListener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author hs
 * @Description: {签名验证}
 * @date 2020/7/17 15:03
 */
public class TheOriginalCheckUtil {
	private final static String HTTP_DOMAIN = "http://mcadmin.ljxmc.top";
	private final static String VERIFY_SIGN = "/api/public/cdk/verifySign";
	/**
	 * 平台上注册的插件名称
	 */
	private final static String PLUGIN_NAME = "DaKong";
	/**
	 * 平台上获取的插件对应秘钥
	 */
	private final static String SECRET_KEY = "1295422278472962048";

	/**
	 * 正版签名验证
	 */
	public static void theOriginalCheck() {
		String sign = main.getInstance().getConfig().getString("key");
		// 获取服务器端口
		int port = 25568;
		// 进行校验
		new BukkitRunnable() {
			@SuppressWarnings("static-access")
			@Override
			public void run() {
				try {
					String urlStr = HTTP_DOMAIN + VERIFY_SIGN + "?sign=" + sign + "&port=" + port + "&pluginName="
							+ PLUGIN_NAME + "&secretKey=" + SECRET_KEY;
					URL url = new URL(urlStr);
					HttpURLConnection connection = (HttpURLConnection) url.openConnection();
					BufferedReader in = new BufferedReader(
							new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
					StringBuilder stringBuilder = new StringBuilder();
					String current;
					while ((current = in.readLine()) != null) {
						stringBuilder.append(current);
					}
					String verifySign = stringBuilder.toString();
					if ("true".equals(verifySign)) {
						// TODO 验证成功进行操作
						Bukkit.getConsoleSender().sendMessage("§5[CS-DaKong]: §a正版验证成功");
						Bukkit.getConsoleSender().sendMessage("§5[CS-DaKong]: §a祝您使用愉快");
						Bukkit.getConsoleSender().sendMessage("§5[CS-DaKong]: §a问题反馈加微信 qingyuzqy");
						super.cancel();
					} else {
						// TODO 验证失败进行操作
						while (true) {
							Bukkit.getConsoleSender().sendMessage("§5[CS-DaKong]: §c正版验证验证失败,联系作者购买,作者QQ:1254841811");
						}
					}
					this.cancel();
				} catch (IOException e) {
					// TODO 网络或者其他问题进行打印消息提醒,并会自动一分钟后重试
				}
			}
		}.runTaskTimerAsynchronously(main.getInstance(), 0, 20 * 60);
	}

}